package org.cleverframe.fastdfs.utils;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class SftpUploader {

    private static final String SERVER = "10.10.180.176"; // 替换为远程服务器的IP地址
    private static final int PORT = 22; // SFTP端口号，默认是22
    private static final String USERNAME = "root"; // 替换为SFTP用户名
    private static final String PASSWORD = "mrjt@123"; // 替换为SFTP密码
    private static final String REMOTE_DIRECTORY = "/data/test_fastdfs"; // 替换为远程服务器上的目标目录

    public static void main(String[] args) {
        String filePath = "/home/yuqing/fastdfs/logfiles/somefile.txt"; // 本地文件路径
        try {
            byte[] bytes = downloadFile(filePath);
            uploadFileToSftpServer(bytes, "somefile.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static byte[] downloadFile(String filePath) throws IOException {
        // 模拟下载文件的方法，实际实现根据需要调整
        return new byte[0];
    }

    private static void uploadFileToSftpServer(byte[] fileBytes, String remoteFileName) {
        Session session = null;
        ChannelSftp channelSftp = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(USERNAME, SERVER, PORT);
            session.setPassword(PASSWORD);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            String remoteFilePath = REMOTE_DIRECTORY + "/" + remoteFileName;
            try (InputStream inputStream = new ByteArrayInputStream(fileBytes)) {
                channelSftp.put(inputStream, remoteFilePath);
                System.out.println("The file is uploaded successfully.");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (channelSftp != null && channelSftp.isConnected()) {
                channelSftp.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
}
